package com.landiao.common.utils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

public class HttpFileDownload
{
	/** 下载远程文件并保存到本地
	 * 
	 * @param remoteFilePath
	 *        远程文件路径
	 * @param localFilePath
	 *        本地文件路径 */
	public static String httpDownload(String remoteFilePath, String localFilePath)
	{
		String str = null;
		URL urlfile = null;
		HttpsURLConnection httpUrl = null;
		File f = new File(localFilePath);
		System.setProperty("jsse.enableSNIExtension", "false");
		try {  
			TrustManager[] tm = { new X509TrustManager() {
				@Override
				public void checkClientTrusted(X509Certificate[] arg0,
						String arg1) throws CertificateException {
				}
				@Override
				public void checkServerTrusted(X509Certificate[] arg0,
						String arg1) throws CertificateException {
				}

				@Override
				public X509Certificate[] getAcceptedIssuers() {
					return null;
				}
			} };
			SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
			sslContext.init(null, tm, new java.security.SecureRandom());
			SSLSocketFactory ssf = sslContext.getSocketFactory();
			urlfile = new URL(remoteFilePath);
			httpUrl = (HttpsURLConnection) urlfile.openConnection();
			httpUrl.setConnectTimeout(1500);
			httpUrl.setSSLSocketFactory(ssf);
			httpUrl.connect();
			String type=httpUrl.getHeaderField("Content-Type");
			InputStream inputStream = httpUrl.getInputStream();
			if(type!=null&&type.indexOf("image")!=1){
				CommUtil.copy(inputStream,new FileOutputStream(f));
			}else{
				inputStream = httpUrl.getInputStream();
				InputStreamReader inputStreamReader = new InputStreamReader(
						inputStream, "utf-8");
				BufferedReader bufferedReader = new BufferedReader(
						inputStreamReader);
				StringBuilder sb = new StringBuilder();
				while ((str = bufferedReader.readLine()) != null) {
					sb.append(str);
				}
				bufferedReader.close();
				inputStreamReader.close();
				inputStream.close();
				inputStream = null;
				str = sb.toString();
			}
			httpUrl.disconnect();
			return str;
		}
		catch (Exception e)
		{
			System.err.println(e.getMessage());
			throw new RuntimeException(e);
		}
	}

	public static void main(String[] argv)
	{
		String url = "";
		httpDownload(url, "D://1.jpg");
	}
}
